package vip.indo.listener;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import vip.indo.service.UserService;

import javax.servlet.ServletContext;

/**
 * 使用ApplicationListener来初始化一些数据到application域中的监听器
 * @Author: tianlianyin
 * @Date: 2024/11/28 16:18
 * @Descripition:
 */
@Component
public class MyServletContextListener implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        //先获取到application上下文
        ApplicationContext applicationContext=contextRefreshedEvent.getApplicationContext();
        //获取对应的service
        UserService userService=applicationContext.getBean(UserService.class);
        //获取application域对象，将查到的信息存放到application域中
        ServletContext application=applicationContext.getBean(ServletContext.class);
        application.setAttribute("user",userService.getUserByName("admin"));
    }
}
